/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.service.impl;

import me.zhengjie.domain.DocPatient;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.DocPatientRepository;
import me.zhengjie.service.DocPatientService;
import me.zhengjie.service.dto.DocPatientDto;
import me.zhengjie.service.dto.DocPatientQueryCriteria;
import me.zhengjie.service.mapstruct.DocPatientMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wcl
* @date 2021-03-25
**/
@Service
@RequiredArgsConstructor
public class DocPatientServiceImpl implements DocPatientService {

    private final DocPatientRepository docPatientRepository;
    private final DocPatientMapper docPatientMapper;

    @Override
    public Map<String,Object> queryAll(DocPatientQueryCriteria criteria, Pageable pageable){
        Page<DocPatient> page = docPatientRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(docPatientMapper::toDto));
    }

    @Override
    public List<DocPatientDto> queryAll(DocPatientQueryCriteria criteria){
        return docPatientMapper.toDto(docPatientRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DocPatientDto findById(Integer id) {
        DocPatient docPatient = docPatientRepository.findById(id).orElseGet(DocPatient::new);
        ValidationUtil.isNull(docPatient.getId(),"DocPatient","id",id);
        return docPatientMapper.toDto(docPatient);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DocPatientDto create(DocPatient resources) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        resources.setGmtCreate(timestamp);
        resources.setGmtUpdate(timestamp);

        String username = SecurityUtils.getCurrentUser().getUsername();
        resources.setUserCreate(username);
        resources.setUserUpdate(username);
        return docPatientMapper.toDto(docPatientRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DocPatient resources) {
        DocPatient docPatient = docPatientRepository.findById(resources.getId()).orElseGet(DocPatient::new);
        ValidationUtil.isNull( docPatient.getId(),"DocPatient","id",resources.getId());
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        resources.setGmtUpdate(timestamp);
        docPatient.copy(resources);
        docPatient.setUserUpdate(SecurityUtils.getCurrentUser().getUsername());
        docPatientRepository.save(docPatient);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            docPatientRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DocPatientDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DocPatientDto docPatient : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("姓名", docPatient.getName());
            map.put(" userId",  docPatient.getUserId());
            map.put("性别，1：男2：女", docPatient.getSex());
            map.put("创建时间", docPatient.getGmtCreate());
            map.put("修改时间", docPatient.getGmtUpdate());
            map.put("创建人", docPatient.getUserCreate());
            map.put("修改人", docPatient.getUserUpdate());
            map.put("年龄", docPatient.getAge());
            map.put("身份证号", docPatient.getIdCard());
            map.put("电话", docPatient.getTel());
            map.put("家庭住址", docPatient.getAddress());
            map.put("工作", docPatient.getJob());
            map.put("初次就诊时间", docPatient.getFristTime());
            map.put("备注", docPatient.getRemark());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}